<template>
  <el-form-item v-bind="formItemAttr" :prop="schema.prop">
    <el-tree-select
      clearable
      v-bind="{ ...treeSelectAttr, ...$attrs }"
      :loading="loading"
      :data="dataSource"
      @change="change"
      style="width: 100%"
    >
    </el-tree-select>
  </el-form-item>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue'
import { lowCodeAttr } from '../../common/util'
import { handleApi } from '../../common/api'
defineOptions({ name: 'TreeSelectCom' })

const instance = getCurrentInstance()

const props = defineProps({
  schema: {
    type: Object,
    required: true
  }
})
const loading = ref()
const dataSource = ref([])
const schema = props.schema
const event = schema.event || {}
const api = schema.api
const formItemAttr = {}

const treeSelectAttr = {}

const formItemIncludeAttrs = ['label', 'prop', 'labelWidth', 'event']
const selectExcludeAttrs = ['searchName', 'event']

for (const key in schema) {
  if (!lowCodeAttr.includes(key)) {
    const value = schema[key]
    if (formItemIncludeAttrs.includes(key)) {
      formItemAttr[key] = value
    } else {
      if (!selectExcludeAttrs.includes(key)) {
        treeSelectAttr[key] = value
      }
    }
  }
}

function change(e) {
  const value = {
    schema,
    value: e
  }
  if (schema?.event?.change) {
    schema.event.change(value)
  }
}

function getDataByApi() {
  if (!api) {
    return
  }
  loading.value = true
  handleApi(api, instance)
    .then((data) => {
      dataSource.value = data
      if (event.loaded) {
        event.loaded(data)
      }
    })
    .finally(() => {
      loading.value = false
    })
}

getDataByApi()
</script>
